<template>
  <div class="resources">
    <h2 class="page-title">资源管理</h2>
    
    <el-card class="page-card">
      <!-- 操作栏 -->
      <div class="action-bar">
        <el-button type="primary" @click="handleAdd(null)" v-if="hasPermission('resource:create')">
          <el-icon><Plus /></el-icon>
          新增资源
        </el-button>
        <el-button @click="expandAll">展开全部</el-button>
        <el-button @click="collapseAll">折叠全部</el-button>
      </div>

      <!-- 树形表格 -->
      <el-table
        :data="tableData"
        style="width: 100%; margin-top: 20px"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        v-loading="loading"
        :default-expand-all="false"
        ref="tableRef"
      >
        <el-table-column prop="name" label="资源名称" width="200" />
        <el-table-column prop="code" label="权限代码" width="200" />
        <el-table-column label="类型" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.type === 'menu'" type="primary" size="small">菜单</el-tag>
            <el-tag v-else-if="row.type === 'page'" type="success" size="small">页面</el-tag>
            <el-tag v-else type="info" size="small">按钮</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="路径" width="200" />
        <el-table-column prop="icon" label="图标" width="100">
          <template #default="{ row }">
            <el-icon v-if="row.icon"><component :is="row.icon" /></el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="sort_order" label="排序" width="80" />
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'info'" size="small">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="240">
          <template #default="{ row }">
            <el-button
              type="success"
              link
              size="small"
              @click="handleAdd(row)"
              v-if="hasPermission('resource:create') && row.type !== 'button'"
            >
              添加子项
            </el-button>
            <el-button
              type="primary"
              link
              size="small"
              @click="handleEdit(row)"
              v-if="hasPermission('resource:update')"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(row)"
              v-if="hasPermission('resource:delete')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="资源类型" prop="type">
          <el-radio-group v-model="form.type" :disabled="!!form.id">
            <el-radio label="menu">菜单</el-radio>
            <el-radio label="page">页面</el-radio>
            <el-radio label="button">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="资源名称" prop="name">
          <el-input v-model="form.name" placeholder="如：用户管理" />
        </el-form-item>
        <el-form-item label="权限代码" prop="code">
          <el-input v-model="form.code" placeholder="如：admin_user:view" />
        </el-form-item>
        <el-form-item label="路径" prop="path" v-if="form.type !== 'button'">
          <el-input v-model="form.path" placeholder="如：/users" />
        </el-form-item>
        <el-form-item label="图标" prop="icon" v-if="form.type !== 'button'">
          <el-input v-model="form.icon" placeholder="如：User" />
        </el-form-item>
        <el-form-item label="排序" prop="sort_order">
          <el-input-number v-model="form.sort_order" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch v-model="form.is_active" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入资源描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { getResourceTree, createResource, updateResource, deleteResource } from '@/api/resources'
import { ElMessage, ElMessageBox } from 'element-plus'

const userStore = useUserStore()

const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增资源')
const formRef = ref(null)
const tableRef = ref(null)

const tableData = ref([])
const currentParent = ref(null)

const form = ref({
  id: null,
  parent_id: null,
  type: 'menu',
  name: '',
  code: '',
  path: '',
  icon: '',
  sort_order: 0,
  is_active: true,
  description: ''
})

const rules = {
  type: [
    { required: true, message: '请选择资源类型', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入资源名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限代码', trigger: 'blur' }
  ]
}

// 权限检查
const hasPermission = (permission) => {
  return userStore.hasPermission(permission)
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getResourceTree()
    if (res.data) {
      tableData.value = res.data
    }
  } catch (error) {
    console.error('Fetch resources error:', error)
  } finally {
    loading.value = false
  }
}

// 展开全部
const expandAll = () => {
  toggleExpand(tableData.value, true)
}

// 折叠全部
const collapseAll = () => {
  toggleExpand(tableData.value, false)
}

// 递归展开/折叠
const toggleExpand = (data, isExpand) => {
  data.forEach(item => {
    if (tableRef.value) {
      tableRef.value.toggleRowExpansion(item, isExpand)
    }
    if (item.children && item.children.length > 0) {
      toggleExpand(item.children, isExpand)
    }
  })
}

// 新增
const handleAdd = (parent) => {
  dialogTitle.value = parent ? `添加子资源（父级：${parent.name}）` : '新增资源'
  currentParent.value = parent
  form.value = {
    id: null,
    parent_id: parent ? parent.id : null,
    type: 'menu',
    name: '',
    code: '',
    path: '',
    icon: '',
    sort_order: 0,
    is_active: true,
    description: ''
  }
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogTitle.value = '编辑资源'
  form.value = {
    id: row.id,
    parent_id: row.parent_id,
    type: row.type,
    name: row.name,
    code: row.code,
    path: row.path,
    icon: row.icon,
    sort_order: row.sort_order,
    is_active: row.is_active,
    description: row.description
  }
  dialogVisible.value = true
}

// 提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        if (form.value.id) {
          await updateResource(form.value.id, form.value)
          ElMessage.success('更新成功')
        } else {
          await createResource(form.value)
          ElMessage.success('创建成功')
        }
        dialogVisible.value = false
        fetchData()
      } catch (error) {
        console.error('Submit error:', error)
      } finally {
        submitting.value = false
      }
    }
  })
}

// 删除
const handleDelete = (row) => {
  if (row.children && row.children.length > 0) {
    ElMessage.warning('该资源下有子资源，请先删除子资源')
    return
  }
  
  ElMessageBox.confirm(`确定要删除资源 "${row.name}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteResource(row.id)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      console.error('Delete error:', error)
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  currentParent.value = null
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.resources {
  width: 100%;
}

.page-title {
  font-size: 24px;
  font-weight: 500;
  color: #333;
  margin-bottom: 20px;
}

.page-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.action-bar {
  display: flex;
  gap: 12px;
}
</style>

